import json
import uuid

from django_filters.rest_framework import DjangoFilterBackend
from django_redis import get_redis_connection
from drf_spectacular.utils import extend_schema
from redis.client import Redis
from rest_framework import response
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter
from demoapp.models import DemoTable
from demoapp.serializers import DemoReqSerializer, DemoResSerializer


@extend_schema(tags=['answer'])
class DemoViewSet(ModelViewSet):
    queryset = DemoTable.objects.all()
    serializer_class = DemoReqSerializer
    lookup_url_kwarg = 'uuid'

    # permission_classes = [] # 移除全局权限
    # pagination_class = None # None不分页; PageNumberPagination 自定分页

    # 列表 get post     -->        list/create
    # 详情 get put patch delete --> retrieve/update/partial-update/destroy

    # 精确匹配
    # filter_backends = [DjangoFilterBackend]  # 默认全局
    filterset_fields = ['req', 'ans','state']  # 查询字段名和查询参数名 ?name=xxxx 字段名也得name, =

    # 模糊匹配
    # filter_backends = [SearchFilter]  # 默认全局
    search_fields =  ['req', 'ans','state']



    @extend_schema('create', request=DemoReqSerializer,responses=DemoResSerializer)
    def create(self, request:Request, *args, **kwargs):
        serializer = DemoReqSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['uuid'] = str(uuid.uuid4())
        serializer.validated_data['ip'] = request.META.get('REMOTE_ADDR')
        obj  = serializer.save()

        redis_cli:Redis = get_redis_connection('default')
        # redis_cli.hset('msg',uuid.uuid4().__str__(),serializer.validated_data['req'])
        redis_cli.lpush('msg',json.dumps({
            'uuid':serializer.validated_data['uuid'],
            'req':serializer.validated_data['req']
        }))
        # return super().create(request, *args, **kwargs) redis.client.Redis

        serializer = DemoResSerializer(instance=obj)
        return Response(serializer.data)

    @extend_schema('retrieve', request=DemoReqSerializer, responses=DemoResSerializer)
    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        serializer = DemoResSerializer(instance=obj)
        return Response(serializer.data)
    @extend_schema('retrieve', request=DemoReqSerializer, responses=DemoResSerializer)
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = DemoResSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = DemoResSerializer(queryset, many=True)
        return Response(serializer.data)
